package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * es测试
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-29
 */
public class CreateIndex {

    public Logger logger = LoggerFactory.getLogger(CreateIndex.class);

    RestHighLevelClient client = EsConfig.getClient();

    /**
     * 创建索引
     */
    @Test
    public void createIndex() throws IOException {
        // 创建索引
        CreateIndexRequest request = new CreateIndexRequest(EsConfig.INDEX_NAME);
        // 分片数为2，备份为1
        Settings.Builder setting = Settings.builder()
                .put("number_of_replicas", 1)
                .put("number_of_shards", 2);
        request.settings(setting);
        request.source(EsConfig.getMapping(), XContentType.JSON);
        boolean b = existIndex(EsConfig.INDEX_NAME);
        if (b) {
            logger.info("该索引：{},已存在", EsConfig.INDEX_NAME);
            logger.info("存在索引则删除该索引,删除成功与否：{}", deleteIndex(EsConfig.INDEX_NAME));
            return;
        }
        // 发起请求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    /**
     * 判断索引是否存在
     *
     * @return boolean
     */
    public boolean existIndex(String indexName) throws IOException {
        GetIndexRequest indexRequest = new GetIndexRequest(indexName);
        return client.indices().exists(indexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 删除索引
     *
     * @param indexName 索引名称
     * @return boolean
     */
    public boolean deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        return client.indices().delete(request, RequestOptions.DEFAULT).isAcknowledged();
    }


}
